import React from 'react';
import { Operator } from './data';
import { message, Modal } from 'antd';
import PubSub from 'pubsub-js';

export const BatchOperator: any = (oparetors: Operator[]) => (
  Component: React.ComponentType<any>,
) => {
  return class extends React.Component<any, any> {
    constructor(props: any) {
      super(props);
    }

    state = {
      selectedRows: [],
    };
    selectionsChange = (selectedRowKeys: any, selectedRows: any) => {
      this.setState({
        selectedRows: selectedRows,
      });
    };

    /*批量操作点击*/
    handleMenuClick = (e: { key: string }) => {
      if (!this.state.selectedRows || this.state.selectedRows.length === 0) {
        return;
      }
      if (!oparetors || oparetors.length === 0) {
        message.error('没有批量方法');
        return;
      }
      let ids = '';
      this.state.selectedRows.forEach((item: any) => {
        ids += item.id + ',';
      });
      if (ids) {
        ids = ids.substring(0, ids.length - 1);
      }
      oparetors.forEach(item => {
        if (item.code === e.key) {
          if (item.custom) {
            item.custom(this.state.selectedRows);
          } else {
            Modal.confirm({
              title: `确定${item.name}吗`,
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                if (item.method) {
                  item.method({ ids: ids }).then((res: any) => {
                    if (res.status === 0) {
                      message.success(`批量${item.name}成功`);
                      PubSub.publish('refresh');
                    } else {
                      message.error(res.msg);
                    }
                  });
                }
              },
            });
          }
        }
      });
    };

    render() {
      return (
        <Component
          {...this.props}
          selectionsChange={this.selectionsChange}
          handleMenuClick={this.handleMenuClick}
        />
      );
    }
  };
};
